import {
  getCompanyInfo,
  submitAuthentication,
  updateCompanyInfo,
} from '@/services/account-center';
import { history, useSearchParams } from '@umijs/max';
import { Button, Col, Form, Input, message, Row, Spin, Typography } from 'antd';
import { useEffect, useState } from 'react';
import UploadComponent from './component/UploadComponent';

const { Text } = Typography;

const SubmitAuthentication = () => {
  const [searchParams] = useSearchParams();
  const [pageData, setPageData] = useState<any>({});
  const [form] = Form.useForm();
  const [alipayNickName, setAlipayNickName] = useState('');
  const [loading, setLoading] = useState(false);
  const [spinning, setSpinning] = useState(false);
  const [imagesData, setImagesData] = useState<Record<string, any>>({
    alipayNickName: null,
    bizLicense: null,
    bizSceneDesc: null,
    businessLicense: null,
    idCardBack: null,
    idCardFront: null,
    merchantCommitment: null,
    otherOneImages: null,
    otherThreeImages: null,
    otherTwoImages: null,
    officeImages1: null,
    officeImages2: null,
    officeImages3: null,
  });

  const getData = (id: any) => {
    setSpinning(true);
    getCompanyInfo({ id })
      .then((res) => {
        setPageData(res);

        setAlipayNickName(res.alipayNickName);
        if (res.businessName) {
          setImagesData({
            ...imagesData,
            ...res,
            disable:
              res.auditStatus === 'init'
                ? res.auditStatus !== 'init'
                : res.auditStatus !== 'init' && res.auditStatus !== 'temp',
            officeImages1: res.officeImages[0],
            officeImages2: res.officeImages[1],
            officeImages3: res.officeImages[2],
          });
          form.setFieldValue('businessName', res.businessName);
          // 有数据但是被拒绝过
          if (res.businessName && res.auditStatus === 'init') {
            form.setFieldsValue({
              bizLicense: true,
              bizSceneDesc: true,
              businessLicense: true,
              idCardBack: true,
              idCardFront: true,
              merchantCommitment: true,
              otherOneImages: true,
              otherThreeImages: true,
              otherTwoImages: true,
              officeImages1: true,
              officeImages2: true,
              officeImages3: true,
            });
          }
        }
      })
      .finally(() => {
        setSpinning(false);
      });
  };

  useEffect(() => {
    if (searchParams.get('id')) {
      getData(searchParams.get('id'));
    }
  }, [searchParams.get('id')]);

  const onFinishFailed = (values: any) => {
    console.log(values);
  };

  const onFinish = (values: any) => {
    const {
      officeImages1,
      officeImages2,
      officeImages3,
      otherTwoImages,
      otherThreeImages,
      otherOneImages,
      merchantCommitment,
      idCardFront,
      idCardBack,
      businessLicense,
      bizSceneDesc,
      bizLicense,
    } = imagesData;
    setLoading(true);
    submitAuthentication({
      officeImages: [officeImages1, officeImages2, officeImages3],
      alipayNickName,
      businessName: values.businessName,
      otherTwoImages,
      otherThreeImages,
      otherOneImages,
      merchantCommitment,
      idCardFront,
      idCardBack,
      businessLicense,
      bizSceneDesc,
      bizLicense,
    })
      .then((res: any) => {
        if (res.success) {
          message.success('提交成功');
          history.back();
        } else {
          message.error(res.resultMessage);
        }
      })
      .finally(() => {
        setLoading(false);
      });
  };

  const renderTitle = () => {
    const obj = {
      auditing: {
        text: '请耐心等待！企业信息信息审核中（预计一个工作日）',
        type: 'warning',
      },
      init: { text: '完善企业信息' },
      fail: { text: '企业信息已被审核拒绝', type: 'danger' },
    } as any;
    return (
      <Text
        className="ml-56 mb-3 text-[20px] font-bold"
        {...obj[pageData.auditStatus]}
      >
        {obj[pageData.auditStatus]?.text}
        <div>
          {pageData.auditStatus === 'fail'
            ? `原因: ${pageData.auditMessage}`
            : ''}
        </div>
      </Text>
    );
  };

  return (
    <div className="h-full bg-white p-4 w-min-[1024px]">
      <Spin spinning={spinning}>
        <div className="flex gap-6">
          {renderTitle()}
          {pageData.auditStatus === 'fail' && (
            <Button
              type="primary"
              onClick={() => {
                updateCompanyInfo({ id: pageData.id }).then((res: any) => {
                  if (res.success) {
                    getData(pageData.id);
                  } else {
                    message.error(res.resultMessage);
                  }
                });
              }}
            >
              修改企业信息
            </Button>
          )}
        </div>
        <Form
          wrapperCol={{ span: 4 }}
          labelCol={{ span: 3 }}
          onFinishFailed={onFinishFailed}
          onFinish={onFinish}
          form={form}
          className="pl-32"
          disabled={pageData.auditStatus === 'auditing'}
        >
          <Form.Item label="企业支付宝">
            <span>{alipayNickName}</span>
          </Form.Item>
          <Form.Item
            label="企业名称"
            name={'businessName'}
            rules={[{ required: true, message: '请输入企业名称' }]}
          >
            <Input placeholder="请输入企业名称" />
          </Form.Item>
          <Form.Item label="网站/APP备案信息" name={'icpInfo'}>
            <Input placeholder="请输入网站/APP备案信息" />
          </Form.Item>
          <Row className="ml-[-35px]">
            <Col span={7}>
              <Form.Item
                name="idCardFront"
                label="法人手持身份证人像面"
                labelCol={{ span: 12 }}
                wrapperCol={{ span: 12 }}
                rules={[
                  { required: true, message: '请上传法人手持身份证人像面' },
                ]}
              >
                <UploadComponent
                  form={form}
                  imagesData={imagesData}
                  setImagesData={setImagesData}
                  fieldName="idCardFront"
                />
              </Form.Item>
            </Col>
            <Col span={7}>
              <Form.Item
                name="idCardBack"
                label="法人手持身份证国徽面"
                labelCol={{ span: 12 }}
                wrapperCol={{ span: 12 }}
                rules={[
                  {
                    required: true,
                    message: '请上传法人手持身份证国徽面',
                  },
                ]}
              >
                <UploadComponent
                  form={form}
                  imagesData={imagesData}
                  setImagesData={setImagesData}
                  fieldName="idCardBack"
                />
              </Form.Item>
            </Col>
          </Row>
          <Row className="ml-[-35px]">
            <Col span={7}>
              <Form.Item
                name="bizLicense"
                label="营业执照"
                labelCol={{ span: 12 }}
                wrapperCol={{ span: 12 }}
                rules={[{ required: true, message: '请上传营业执照' }]}
              >
                <UploadComponent
                  form={form}
                  imagesData={imagesData}
                  setImagesData={setImagesData}
                  fieldName="bizLicense"
                />
              </Form.Item>
            </Col>
            <Col span={7}>
              <Form.Item
                name="businessLicense"
                label="法人手持营业执照"
                labelCol={{ span: 12 }}
                wrapperCol={{ span: 12 }}
                rules={[{ required: true, message: '请上传法人手持营业执照' }]}
              >
                <UploadComponent
                  form={form}
                  imagesData={imagesData}
                  setImagesData={setImagesData}
                  fieldName="businessLicense"
                />
              </Form.Item>
            </Col>
          </Row>

          {/* <Row>
          <Col span={7}> */}
          <Form.Item
            label="办公室照片"
            name={'officeImages'}
            wrapperCol={{ span: 12 }}
            rules={[
              {
                required: true,
                validator(rule, value, callback) {
                  if (
                    !imagesData.officeImages1 ||
                    !imagesData.officeImages2 ||
                    !imagesData.officeImages3
                  ) {
                    return callback('请上传3张办公室照片');
                  }
                  callback();
                },
              },
            ]}
          >
            <div className="flex gap-3">
              <UploadComponent
                form={form}
                imagesData={imagesData}
                setImagesData={setImagesData}
                fieldName="officeImages1"
                imageWidth={200}
              />
              <UploadComponent
                form={form}
                imagesData={imagesData}
                setImagesData={setImagesData}
                fieldName="officeImages2"
                imageWidth={200}
              />
              <UploadComponent
                form={form}
                imagesData={imagesData}
                setImagesData={setImagesData}
                fieldName="officeImages3"
                imageWidth={200}
              />
            </div>
            <div className="mt-3">
              上传 3 张截图，
              <span className="text-[red]">
                1张门头照（门牌号和企业门牌需要一起拍进去）
              </span>
              ，2张内景照，支持png、jpg格式，单张不超过5MB
            </div>
          </Form.Item>
          {/* </Col>
        </Row> */}
          <Form.Item
            label="商务业务说明"
            name={'bizSceneDesc'}
            rules={[{ required: true, message: '请上传商务业务说明' }]}
          >
            <UploadComponent
              form={form}
              imagesData={imagesData}
              setImagesData={setImagesData}
              fieldName="bizSceneDesc"
            />
          </Form.Item>
          <Form.Item
            label="商户承诺书"
            name={'merchantCommitment'}
            rules={[{ required: true, message: '请上传商户承诺书' }]}
          >
            <UploadComponent
              form={form}
              imagesData={imagesData}
              setImagesData={setImagesData}
              fieldName="merchantCommitment"
            />
          </Form.Item>
          <Form.Item
            label="其他资质照片"
            name={'otherImages'}
            wrapperCol={{ span: 12 }}
          >
            <div className="flex gap-3">
              <UploadComponent
                form={form}
                imagesData={imagesData}
                setImagesData={setImagesData}
                fieldName="otherOneImages"
                imageWidth={200}
              />
              <UploadComponent
                form={form}
                imagesData={imagesData}
                setImagesData={setImagesData}
                fieldName="otherTwoImages"
                imageWidth={200}
              />
              <UploadComponent
                form={form}
                imagesData={imagesData}
                setImagesData={setImagesData}
                fieldName="otherThreeImages"
                imageWidth={200}
              />
            </div>
            <div className="mt-3">
              上下游合作业务协议，历史下发流水截图等 非必填
            </div>
          </Form.Item>
          <Form.Item
            className={`${
              pageData.auditStatus === 'init' || pageData.auditStatus === 'temp'
                ? ''
                : 'hidden'
            }`}
          >
            <Button
              className="ml-44 w-32"
              type="primary"
              htmlType="submit"
              loading={loading}
            >
              提交
            </Button>
          </Form.Item>
        </Form>
      </Spin>
    </div>
  );
};

export default SubmitAuthentication;
